﻿using System.Threading;
namespace System.Web
{
    internal class ReadWriteObjectLock
    {
        private int _lock;

        internal ReadWriteObjectLock() { }

        internal virtual void AcquireRead()
        {
            lock (this)
            {
                while (_lock == -1)
                {
                    try { Monitor.Wait(this); continue; }
                    catch (ThreadInterruptedException) { continue; }
                }
                _lock++;
            }
        }

        internal virtual void AcquireWrite()
        {
            lock (this)
            {
                while (_lock != 0)
                {
                    try { Monitor.Wait(this); continue; }
                    catch (ThreadInterruptedException) { continue; }
                }
                _lock = -1;
            }
        }

        internal virtual void ReleaseRead()
        {
            lock (this)
            {
                _lock--;
                if (_lock == 0)
                    Monitor.PulseAll(this);
            }
        }

        internal virtual void ReleaseWrite()
        {
            lock (this)
            {
                _lock = 0;
                Monitor.PulseAll(this);
            }
        }
    }
}
